package com.tuanzi.loan.web.bean.family;

import static com.tuanzi.loan.business.constants.DictionaryCode.UNION_SERIAL;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import lombok.Data;
import lombok.EqualsAndHashCode;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.constants.DictionaryCode;
import com.tuanzi.loan.business.entity.common.CommProductChannel;
import com.tuanzi.loan.business.entity.common.CommProductId;
import com.tuanzi.loan.business.entity.family.BlacklistType;
import com.tuanzi.loan.business.entity.family.RegisterRecommendActivity;
import com.tuanzi.loan.business.service.family.BlacklistTypeService;
import com.tuanzi.loan.business.service.family.RegisterRecommendActivityService;
import com.tuanzi.loan.business.service.family.UserMobileExportService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.family.UserMobileExportSearchRequest;
import com.tuanzi.loan.vo.response.family.UserMobileExportSearchResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.family.UserMobileExportLazyDataModel;
import com.tuanzi.server.loan_base.util.DateUtils;
/**
 * 用户手机号导出处理
 * @author Xumiaohang 2017/11/10
 *
 */
@Data
@Debug
@Component
@ViewScoped
@Transactional
@EqualsAndHashCode(callSuper = true)
@SuppressWarnings("serial")
public class UserMobileExportBean extends JSFListingBean<UserMobileExportSearchRequest, UserMobileExportSearchResponse> {

	@Autowired
	private UserMobileExportService userMobileExportService;
	@Autowired
	private RegisterRecommendActivityService registerRecommendActivityService;
	@Autowired
	private BlacklistTypeService blacklistTypeService;
	
	private List<RegisterRecommendActivity> activityTypes;
	private List<BlacklistType> blacklistTypes;
	private List<CommProductId> commProductIds;
	private List<CommProductChannel> commProductChannels;
	// 内存数据超过3000条会刷新到硬盘
	private static final Integer DISK_COUNT=3000;  
	//分页查询，页大小
	private static final Integer PAGE_SIZE=8000;  
	
	@PostConstruct
	private void init() {
		initLazyDataModel();
		activityTypes=registerRecommendActivityService.findAll();
		blacklistTypes=blacklistTypeService.findAll();
		commProductIds=super.getCommProductIds();
		commProductChannels=super.getCommProductChannels();
	}

	public void onReset(){
		initLazyDataModel();
	}
	
	public void onCheck(){
		userMobileExportService.onCheck();
	}
	
	 @Override
	 protected List<String> getDictionaryCodes() {
	    return Lists.newArrayList(UNION_SERIAL);
	 }
	 
	 private void initLazyDataModel() {
		 $ = new UserMobileExportSearchRequest();
		 lazyDataModel = new UserMobileExportLazyDataModel($);
	 }
	 
	// 导出excel数据
	public void exportExcel() {
		try {
			Integer offset = 0;
			//sheet的数量
			Integer sheetCount=1;  
			//循环导出数据的次数，从0开始
			Integer exportCount=0; 
			Sheet sheet = null;
			Row titleRow = null;
			SXSSFWorkbook workbook = new SXSSFWorkbook(DISK_COUNT); 
			List<UserMobileExportSearchResponse> pageData = null;
			while(true){
				// 分页获取数据集合
				pageData = userMobileExportService.getExportData($,offset,PAGE_SIZE); 
				if (pageData != null && pageData.size() > 0) {
					//一个sheet存放80000条记录
					if(exportCount % 10 == 0){  
						// 创建sheet和设置列标题
						sheet=workbook.createSheet("data" + sheetCount);
						titleRow = sheet.createRow(0);
						setTitleRow(titleRow);
						sheetCount++;
					}
					// 导出数据的操作
					exportOperate(sheet, pageData, pageData.size());
					exportCount++;
					offset = offset + PAGE_SIZE;
				}else{
					break;
				}
			}
			// 以输出流导出数据
			export(workbook);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 设置列标题
	private void setTitleRow(Row titleRow) {
		String[] titles = { "推广页登记时间", "app注册时间", "活动类型", "活动标识", "所属产品",
				"所属渠道", "平台", "用户类型", "黑名单状态", "屏蔽联登活动", "手机号" };
		for (int k = 0; k < titles.length; k++) {
			Cell titleCell = titleRow.createCell(k);
			titleCell.setCellValue(titles[k]);
		}
	}
	
	// 导出数据的操作
	private void exportOperate(Sheet sheet, List<UserMobileExportSearchResponse> pageData, int count) {
		for (int j = 0; j < count; j++) {
			Row row = sheet.createRow(sheet.getPhysicalNumberOfRows());
			Cell cell1 = row.createCell(0);
			Date recordTime = pageData.get(j).getRecordTime();
			if (recordTime != null) {
				cell1.setCellValue(DateUtils.formatDateToYyyyMMdd(recordTime));
			}
			Cell cell2 = row.createCell(1);
			Date registerTime = pageData.get(j).getRegisterTime();
			if (registerTime != null) {
				cell2.setCellValue(DateUtils.formatDateToYyyyMMdd(registerTime));
			}
			Cell cell3 = row.createCell(2);
			cell3.setCellValue(pageData.get(j).getActivityType());
			Cell cell4 = row.createCell(3);
			cell4.setCellValue(pageData.get(j).getActivityId());
			Cell cell5 = row.createCell(4);
			cell5.setCellValue(pageData.get(j).getProductId());
			Cell cell6 = row.createCell(5);
			cell6.setCellValue(pageData.get(j).getChannelId());
			Cell cell7 = row.createCell(6);
			cell7.setCellValue(pageData.get(j).getPlatform());
			Cell cell8 = row.createCell(7);
			cell8.setCellValue("0".equals(pageData.get(j).getUserType()) ? "注册用户"
					: "登记未注册用户");
			Cell cell9 = row.createCell(8);
			cell9.setCellValue(pageData.get(j).getBlacklist());
			Cell cell10 = row.createCell(9);
			cell10.setCellValue(translate(DictionaryCode.UNION_SERIAL,
					pageData.get(j).getUnionLogin()));
			Cell cell11 = row.createCell(10);
			cell11.setCellValue(pageData.get(j).getUserId());
		}
	}
	
	// 输出流导出数据
	private void export(SXSSFWorkbook workbook) throws IOException {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalContext = facesContext.getExternalContext();
		externalContext.setResponseContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		externalContext.setResponseHeader("Content-Disposition", "attachment; filename=UserMobileData.xlsx");
		workbook.write(externalContext.getResponseOutputStream());
		facesContext.responseComplete();
	}
		
}